
import { Image, List, InfiniteScroll } from 'antd-mobile'
import { useState, useEffect } from 'react'
import { getListHttp } from '@/api/homeapi/homeapi.ts';
import { articlesData, ListRes, HomeListProps } from '@/api/homeapi/index'
import {useNavigate} from 'react-router-dom'







function HomeList({ id }: HomeListProps) {
const navigate=useNavigate()
  const [hasMore, sethasMore] = useState(false)
  const [listRes, setListRes] = useState<ListRes>({
    pre_timestamp: '' + new Date().getTime(),
    results: []
  })

  useEffect(() => {
    const listdata = {
      channel_id: id,
      timestamp: listRes.pre_timestamp
    }
    handGetListHttp(listdata)
  }, [])

  const handGetListHttp = async (data: articlesData) => {
    try {
      const res = await getListHttp(data);
      console.log(res.data)
      setListRes(res.data);
      sethasMore(true)
    } catch (error) {
      console.error('Error fetching channels:', error);
    }
  }


  async function loadMore() {
    console.log('见底啦')
    const listdata = {
      channel_id: id,
      timestamp: listRes.pre_timestamp
    }
    handleHitBottomHttp(listdata)
  }


  const handleHitBottomHttp = async (data: articlesData) => {
    try {
      const res = await getListHttp(data);
      console.log(res.data.results,res.data.pre_timestamp)
      setListRes({
        results:[...listRes.results,...res.data.results],
        pre_timestamp:res.data.pre_timestamp,
      })
      if (res.data.results.length === 0) {
        sethasMore(false)
      }
    } catch (error) {
      console.error('Error fetching channels:', error);
    }
  }


  const handelDetail=(id:string)=>{
    console.log('跳转页面',id)
    navigate(`/detail?id=${id}`)
  }

  return (
    <>
      <List>
        {listRes.results.map(user => (
          <List.Item
          onClick={()=>handelDetail(user.art_id)}
            key={user.art_id}
            prefix={
              <Image
                src={user.cover.images?.[0]}
                style={{ borderRadius: 20 }}
                fit='cover'
                width={40}
                height={40}
              />
            }
            description={user.pubdate}
          >
            {user.title}
          </List.Item>
        ))}
      </List>
      {/* 触底了会触发loadMore函数，hasMore为true的时候才会有触底就触发函数的功能，threshold设置距离底部多少px就触发函数，InfiniteScroll需满足以上三个条件才能触底就请求 */}
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={5} />
    </>
  )
}

export default HomeList
